import _ from 'lodash';
import { connect } from 'umi';
import { useEffect, useState } from 'react';
import { Button, Card, Row, Space, Spin, Table } from 'antd';
import { SearchOutlined, DiffOutlined, SendOutlined } from '@ant-design/icons';

import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { Descriptions, useDescriptions } from '@/components/Descriptions';

import '../common/styles.less';
import SourceListModal from './SourceListModal';
import ExpertsListModal from './ExpertsListModal';
import { splitExpertData } from '../common/Format';
import ExpertsAddDeputyModal from './ExpertsAddDeputyModal';
import { getBidColumns, getExpertsColumns } from '../mconfig';
import { addExpertsSerivice, editExpertsSerivice, getExpertsSerivice } from '../services';

const UpdateView = ({ curRes, locationProps }) => {
  let { state } = locationProps;
  let { pageType, record } = state;

  let preflxCls = 'source-bidevaluation'; /**CSS样式*/

  const [isShowBidState, setIsShowBidState] = useState(false); /**添加采购人评标代表弹窗渲染状态*/
  const [isShowExpertsState, setIsShowExpertsState] = useState(false); /**选择评标专家弹窗渲染状态*/

  const [isShowSourceListModal, setIsShowSourceListModal] = useState(false); /**是否显示选择标包弹窗*/
  const [isShowRemoveModal, setIsShowRemoveModal] = useState<Record<string, any>>({}); /**是否显示【删除采购人评标专家弹窗】*/
  const [isShowRemoveExpertModal, setIsShowRemoveExpertModal] = useState<Record<string, any>>({}); /**是否显示【删除评标专家弹窗】*/

  const [detailInfo, setDetailInfo] = useState<Record<string, any>>({});
  const [expertsList, setExpertsList] = useState<Record<string, any>[]>([]); /**列表数据*/
  const [packObj, setPackObj] = useState<Record<string, any>>({}); /**保存一份从标包弹窗中选择的/详情返回的标包数据*/

  /**表格配置*/
  const [config, methods] = useDescriptions({
    name: 'source-experts',
    labelWidth: 240,
    schemas: [
      {
        label: '一、相关采购项目',
        field: 'Title',
        component: 'Title',
      },
      {
        label: '标包名称',
        field: 'packName',
        component: 'Input',
        placeholder: '请选择',
        required: true,
        disabled: true,
        contentAfter: (
          <a>
            <SearchOutlined onClick={() => setIsShowSourceListModal(true)} />
          </a>
        ),
      },
      {
        label: '标包编号',
        field: 'packCode',
        component: 'Input',
        placeholder: '自动带出',
        disabled: true,
      },
    ],
  });

  /**添加接口*/
  const { addExpertsRun, addExpertsLoading } = addExpertsSerivice((res) => {});

  /**编辑接口*/
  const { editExpertsRun, editExpertsLoading } = editExpertsSerivice((res) => {});

  /**详情接口*/
  const { getExpertsRun, getExpertsLoading } = getExpertsSerivice((res) => {
    if (res?.msgFlag) {
      setDetailInfo(res?.obj); //详情存一份
      setExpertsList(res?.obj?.mpurchaseSourceExpertList || []); //展示的数据
    }
  });

  /** 移除评标人代表 */
  const onRemoveBid = (record, index: number) => {
    setIsShowRemoveModal({
      isShow: true,
      resObj: record,
      recordIndex: index,
    });
  };

  /** 移除专家 */
  const onRemoveExperts = (record, index: number) => {
    setIsShowRemoveExpertModal({
      isShow: true,
      resObj: record,
      recordIndex: index,
    });
  };

  /** 采购人评标代表弹窗保存事件 */
  const onSaveBidData = (value: Record<string, any>) => setExpertsList([...expertsList, { ...value, sourceType: 1 }]);

  /** 评标专家弹窗保存事件 */
  const onSaveExpertsData = (value: Record<string, any>[]) => setExpertsList([...expertsList, ...value]);

  /** 标包列表弹窗的确定 */
  const onSaveModal = (resObj) => {
    let { applyID, projectID, projectCode, projectName, projectSum, purchProjectName, purchProjectCode, id } = resObj;

    // 设置表单信息
    methods?.setFieldsValue({ packName: resObj?.packName, packCode: resObj?.packCode });

    // 保存一份标包信息
    setPackObj({
      applyID,
      projectID,
      projectCode,
      projectName,
      projectSum,
      purchProjectName,
      purchProjectCode,
      sourceID: id,
    });
  };

  /** 暂存按钮 */
  const onSave = () => {
    if (pageType == 'add') {
      onAdd();
    } else if (pageType == 'edit') {
      onEdit();
    }
  };

  /**添加方法*/
  const onAdd = () => {
    let resObj = {
      ...packObj,
      mpurchaseSourceExpertList: expertsList,
    };
    addExpertsRun(resObj);
  };

  /**编辑方法*/
  const onEdit = () => {
    // let delIds: any[] = []; // bottom的删除id
    // let old_data = allList?.[PackIndex]?.mpurchaseSourceExpertList;
    // let allIds = allList?.[PackIndex]?.nowMpurchaseSourceExpertList?.map((item) => item?.id);
    // old_data?.forEach((item) => {
    //   if (!allIds?.includes(item?.id)) {
    //     delIds?.push(item?.id);
    //   }
    // });
    // let resObj = {
    //   ...result,
    //   delIds: delIds?.join(','),
    //   versionNum: old_data?.[0]?.versionNum,
    // };
    // editExpertsRun(resObj); //单个编辑
  };

  /**详情方法*/
  const onDetail = (obj) => {
    getExpertsRun(obj);
  };

  /** 提交按钮 */
  const onSubmit = () => {};

  /**监听器*/
  useEffect(() => {
    if (pageType == 'detail' || pageType == 'edit') {
      onDetail({ id: record?.sourceID });
    }
  }, [pageType]);

  return (
    <>
      <Card
        title={'组建评标委员会'}
        className={preflxCls + '-RootBoxDiv'}
        actions={[
          <Space>
            <Button
              type="primary"
              // icon={<DiffOutlined />}
              onClick={onSave}
            >
              暂存
            </Button>
            <Button
              type="primary"
              // icon={<SendOutlined />}
              onClick={onSubmit}
            >
              提交
            </Button>
          </Space>,
        ]}
      >
        <Spin spinning={getExpertsLoading || editExpertsLoading || addExpertsLoading}>
          <ScrollBarLayout>
            <div className={'source-bidevaluation-desc'}>
              <Descriptions config={config} />
              <div className={'source-bidevaluation-row'}>
                <Row key={'bidevaluation'}>
                  <div className={'source-bidevaluation-item-title'}>二、采购人评标代表</div>
                  <div className={'list-table'}>
                    <Table
                      bordered
                      size="small"
                      columns={getBidColumns({
                        onRemove: onRemoveBid,
                        onOpen: () => setIsShowBidState(true),
                        isShowOpenBtn: true,
                      })}
                      dataSource={splitExpertData(expertsList, 1)}
                      loading={false}
                      scroll={{ x: 550 }}
                      pagination={false}
                    />
                  </div>
                </Row>
                <Row key={'bid'} className={'source-bidevaluation-row-bid'}>
                  <div className={'source-bidevaluation-item-title'}>三、评标专家代表</div>
                  <div className={'list-table'}>
                    <Table
                      bordered
                      size="small"
                      columns={getExpertsColumns({
                        onRemove: onRemoveExperts,
                        onOpen: () => setIsShowExpertsState(true),
                        isShowOpenBtn: true,
                      })}
                      dataSource={splitExpertData(expertsList, 0)}
                      loading={false}
                      scroll={{ x: 500 }}
                      pagination={false}
                      rowKey={'id'}
                    />
                  </div>
                </Row>
              </div>
            </div>
          </ScrollBarLayout>
        </Spin>
      </Card>

      {/* 添加采购人代表弹窗 */}
      {isShowBidState && <ExpertsAddDeputyModal onSave={onSaveBidData} onClose={() => setIsShowBidState(false)} />}

      {/* 选择专家弹窗 */}
      {isShowExpertsState && (
        <ExpertsListModal onSave={onSaveExpertsData} onClose={() => setIsShowExpertsState(false)} dataSource={splitExpertData(expertsList, 0)} />
      )}

      {/* 删除采购人评标代表弹窗 */}
      {isShowRemoveModal?.isShow && (
        <TipsErrorModalNew
          modalTip={
            <>
              <span>
                <p>
                  是否删除，姓名为【<span style={{ color: 'red' }}>{isShowRemoveModal?.resObj?.fullName}</span>
                  】的采购人评标代表
                </p>
                <p>注意：此操作不可恢复</p>
              </span>
            </>
          }
          modalLoading={false}
          tipTextColor={'#000'}
          bodyWidth={0.25}
          modalTitle="删除采购人评标代表"
          onClose={() => setIsShowRemoveModal({})}
          modalOnOK={() => {
            const packExpertList = expertsList;
            const delIndex = packExpertList?.findIndex((item) => {
              if ('id' in item && 'id' in isShowRemoveModal?.resObj) {
                return item?.id == isShowRemoveModal?.resObj?.id;
              } else if ('mockID' in item && 'mockID' in isShowRemoveModal?.resObj) {
                return item?.mockID == isShowRemoveModal?.resObj?.mockID;
              }
            });
            packExpertList.splice(delIndex, 1);
            setExpertsList(packExpertList);
          }}
        />
      )}

      {/* 删除评标专家弹窗 */}
      {isShowRemoveExpertModal?.isShow && (
        <TipsErrorModalNew
          modalTip={
            <>
              <span>
                <p>
                  是否删除，姓名为【<span style={{ color: 'red' }}>{isShowRemoveExpertModal?.resObj?.fullName}</span>
                  】的评标专家
                </p>
                <p>注意：此操作不可恢复</p>
              </span>
            </>
          }
          modalLoading={false}
          tipTextColor={'#000'}
          bodyWidth={0.25}
          modalTitle="删除评标专家"
          onClose={() => setIsShowRemoveExpertModal({})}
          modalOnOK={() => {
            const packExpertList = expertsList;
            const delIndex = packExpertList?.findIndex((item) => {
              if ('id' in item && 'id' in isShowRemoveExpertModal?.resObj) {
                return item?.id == isShowRemoveExpertModal?.resObj?.id;
              } else if ('mockID' in item && 'mockID' in isShowRemoveExpertModal?.resObj) {
                return item?.mockID == isShowRemoveExpertModal?.resObj?.mockID;
              }
            });
            packExpertList.splice(delIndex, 1);
            setExpertsList(packExpertList);
          }}
        />
      )}

      {/* 选择实施列表弹窗 */}
      {isShowSourceListModal && <SourceListModal onClose={() => setIsShowSourceListModal(false)} onSave={onSaveModal} curRes={curRes} />}
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdateView);
